package objects;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import objects.visualization.Block;
import objects.visualization.ListBlock;
import objects.visualization.TextBlock;

public class GruClass extends IDObject {
	public DataObject nativeClass;
	public GruClass parentClass;
	public ArrayList<Field> fields = new ArrayList<Field>();
	public ArrayList<Method> methods = new ArrayList<Method>();
	public ArrayList<Field> allFields = new ArrayList<Field>();
	public ArrayList<AddressedObject> classObjects = new ArrayList<AddressedObject>();

	public GruClass( DataObject nativeClass ) {
		this.nativeClass = nativeClass;
		this.gruClass = classClass;
	}
	
	@Override
	public void io() throws IOException {
		iD = stringIO( iD );
		parentClass = objectIO( parentClass );
		listIO( fields );
		listIO( methods );
	}

	@Override
	public GruClass toGruClass() {
		return this;
	}
	
	@Override
	public DataObject newObject() {
		return new GruClass( null );
	}

	public void addFields( GruClass gruClass ) {
		if( gruClass.parentClass != null ) addFields( gruClass.parentClass );
		for( Field field : fields ) {
			field.index = allFields.size();
			allFields.add( field );
		}
	}	

	public void print( PrintWriter writer ) {
		writer.println( headerCode() + "{" );
		for( Field field : fields ) {
			writer.println( "\t" + field.headerCode() + ";" );
		}
		for( Method method : methods ) {
			String params = "";
			for( Field field : method.parameters ) {
				writer.print( field.headerCode() + ( params.isEmpty() ? "" :  ", " ) );
			}
			writer.println( "\t" + method.headerCode() + "( " + params + " ) {" );
			for( Module module : method.modules ) {
				writer.println( module.toCode( "\t\t" ) );
			}
			writer.println( "}" );
			writer.println();
		}
		writer.println( "}" );
	}
	
	public Block toBlock() {
		ListBlock blocks = new ListBlock( true, true );
		blocks.add( new TextBlock( this, headerCode(), 0 ) );
		for( Field field : fields ) {
			blocks.add( new TextBlock( field, field.headerCode(), 1 ) );
		}
		for( Method method : methods ) {
			blocks.add( method.toBlock() );
		}
		return blocks;
	}

	private String headerCode() {
		return "class " + iD + ( parentClass == nullObject ? "" : " extends " + parentClass.iD );
	}
}
